package com.kcth.sylyg08.rest;

import com.kcht.adp.common.log.Logger;
import com.kcht.adp.common.utils.BeanUtils;
import com.kcht.sylyg08.service.IGenerateEpcNo;

import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.zip.GZIPOutputStream;

/**
 * @Package: com.kcth.sylyg08.rest
 * @Description: 获取内部生成 EPC 码
 * @Author: lenovo
 * @CreateDate: 2019/5/20 13:00
 */
@Path("/getEpcNo")
@RequestScoped
@Transactional(value= Transactional.TxType.NOT_SUPPORTED,rollbackOn=Exception.class)
public class GetEpcNo {
    @Context
    private HttpServletRequest request;
    @Inject
    private Logger logger;
    @EJB
    IGenerateEpcNo generateEpcNo;

    @GET
    @Produces("application/json")
    public Object getEPCNo() throws Exception {
        String realIP = Optional.ofNullable(request.getHeader("X-Real-IP")).orElse(request.getRemoteAddr());
        logger.info(String.format("[%s]=>GET请求地址:%s/%s", realIP, "GetEpcNo", "getProductUniqueIdentifier"));
        logger.info(String.format("[%s]=>GET请求参数:%s", realIP, BeanUtils.ignoreBigProperty(getAllRequestParam(request))));
        /** 生成标签的 EPC 码 */
        Map<String,String> m = new HashMap<>(1);
        m.put("epc",generateEpcNo.getEPCNo());
        logger.info("return =>" + BeanUtils.ignoreBigProperty(m));
        return m;
    }

    /**
     * 获取客户端请求参数中所有的信息
     * @param request
     * @return
     */
    private Map<String, String> getAllRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<String, String>();
        Enumeration<?> temp = request.getParameterNames();
        if (null != temp) {
            while (temp.hasMoreElements()) {
                String en = (String) temp.nextElement();
                String value = request.getParameter(en);
                res.put(en, value);
                //如果字段的值为空，判断若值为空，则删除这个字段>
                if (null == res.get(en) || "".equals(res.get(en))) {
                    res.remove(en);
                }
            }
        }
        return res;
    }
}